<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="upload_elements">
    <div class="steps">
      <el-steps :active="active" style="width: 100%" align-center>
        <el-step title="文件上传" />
        <el-step title="数据的处理" />
        <!-- <el-step title="数据的转换" /> -->
        <el-step title="完成" />
      </el-steps>
    </div>
    <div class="upload" v-show="active === 1" v-loading="uploadLoading" element-loading-text="压缩包解压中...">
      <div class="upload_content">
        <el-form size="small" label-width="120">
          <el-form-item label="机型：" required>
            <el-select style="width: 480px" v-model="uploadForm.modelNumber" clearable placeholder="请选择机型" @change="modelChange">
              <el-option v-for="item in modelNumberList" :label="item.name" :value="item.mark" :key="item.mark"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批次号：" required>
            <el-select v-if="!uploadForm.modelNumber" style="width: 480px" v-model="uploadForm.batchNumber" filterable clearable placeholder="请选择批次号">
              <el-option v-for="(item, index) in batchList" :label="batchList[index]" :value="batchList[index]" :key="index"></el-option>
            </el-select>
            <el-autocomplete
              v-else
              style="width: 480px"
              v-model="uploadForm.batchNumber"
              :fetch-suggestions="querySearch"
              clearable
              class="inline-input w-50"
              placeholder="请输入批次号"
            />
          </el-form-item>
          <!-- <el-form-item v-if="props.pageType === 'importComp'" label="部段：" required>
            <el-select style="width: 480px" v-model="uploadForm.sectionNumber" clearable placeholder="请选择部段号">
              <el-option v-for="item in sectionList" :label="item.name + '[' + item.mark + ']'" :value="item.mark" :key="item.mark"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="props.pageType !== 'importComp'" label="索引文件名：" >
            <el-input style="width: 480px" v-model="uploadForm.indexFileName" placeholder="请输入索引文件名，如：C919_10002_D20200910"/>
          </el-form-item> -->
          <el-form-item label="模型上传：" required>
            <el-upload class="upload-demo" style="width:480px;height:150px;" drag :file-list="uploadFiles" :beforeUpload="beforeUpload" :http-request="componentImport" accept=".zip,.rar">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text" style="text-align: left;">
                注意事项：<br>
                1.只支持.zip、.rar压缩包文件上传。<br>
                2.压缩包解压后将读取根目录下的所有文件和其子文件夹“P_load”里的文件。<br>
                3.根目录下以“Model”开头的文件名将放入到“全机”文件类型中。<br>
                4.根目录下以第一个“_”+“S”命名的文件将根据部段的命名规则放入到对应部段文件类型中。<br>
                5.“P_load”文件夹的文件将放入到“气密卡”文件类型中。<br>
                6.只存入.dat、.out、.bdf类型的文件，其余格式文件将自动剔除。<br>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="uploadLoading" element-loading-text="确认上传中..." class="upload_check" v-show="active === 2">
      <DataHandle ref="handleModelData" v-if="active === 2" :data="handleZipData" :active="active" />
    </div>
    <!-- <div class="upload_list" v-show="active === 3" v-loading="uploadLoading" element-loading-text="数据导入中...">
      <DataTransform :batchNumber="uploadForm.batchNumber" :data="zipData" v-if="active === 3" :active="active" @change="dataChange" />
    </div> -->
    <div class="upload_success" v-show="active === 3">
      <div class="upload_success_message">
        <el-icon size="48" color="#67C23A"><CircleCheck /></el-icon>
        <h3 class="res-statistic">
          本次共上传文件 <el-link type="primary">{{ totalCount }}</el-link> 笔，
          <template v-if="notFilterCount > 0">其中通过数据质量检测的有 <el-link type="success">{{ notFilterCount }}</el-link> 条；</template>
          <template v-if="filterCount > 0">未通过数据质量检测的有 <el-link type="danger">{{ filterCount }}</el-link> 条。具体如下：</template>
        </h3>
      </div>
      <div class="model-batch">
        <label for="">机型：</label><span>{{ uploadForm.modelNumber }}</span>
        <label for="">批次：</label><span>{{ uploadForm.batchNumber }}</span>
      </div>
      <!-- <FileTree :data="importedData" v-if="active === 4" :active="active" /> -->
      <ResultTreeTable v-if="active === 3" :treeVo="treeVo" :isDialog="false" />
    </div>
    <div class="option_btn">
      <el-button size="small" @click="cancel" v-show="active === 1" :disabled="uploadLoading">取消</el-button>
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="active === 1" @click="step('next', 2)">下一步</el-button>
      <!-- <el-button size="small" type="primary" @click="exportExcel" v-show="active === 2">导出数据</el-button> -->
      <el-button size="small" :disabled="uploadLoading" v-show="active === 2" @click="step('pre', 1)">返回上一步</el-button>
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="active === 2" @click="comfirmImport">确认上传</el-button>
      <el-button size="small" type="primary" v-show="active === 3" @click="finish">完成</el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" title="文件解析中..." width="500" :show-close="false">
      <el-table v-loading="dialogFormVisible" :data="[]" style="width: 100%">
      </el-table>
      <p style="text-align: center;">文件解析中，请耐心等待。</p>
    </el-dialog>
  </div>
</template>
<script  setup name="ImportModelData">
import DataHandle from './DataHandle.vue';
import DataTransform from './DataTransform.vue';
import ResultTreeTable from './ResultTreeTable.vue';
import { getBatchNo, getMeshModelStructureList, uploadMeshModelZip, confirmUpload } from '@/api/dataAcquisition';

const emits = defineEmits(['handleEvent']);
const props = defineProps(['tableName']);
const uploadLoading = ref(false);
const active = ref(1);
const basicInfo = ref({ structureModelId: '', taskName: '', name: '' });
const structureModel = ref([]);// 机型列表
const structureModelAll = ref([]);// 机型结构列表
const chooseRef = ref(null);
const computedRef = ref(null);
const chooseData = ref(null);
const computedData = ref(null);
const finishData = ref(null);
const loading = ref(false);
const updateFlag = ref(false);
const checkedTreeData = ref([]);
const computedUpdate = ref(false);
const batchNumber = ref(''); // 默认批次
const uploadForm = ref({
  batchNumber: undefined,
  modelNumber: undefined
})
const modelNumberList = ref([]);
const batchList = ref([]);
const uploadFiles = ref([]);
const dialogFormVisible = ref(false);
const handleZipData = ref(null);
// 导入确认数据
const confirmImportTableData = ref([]);
const handleModelData = ref(null);
const uploadResult = ref(null); // 上传结果
const filterCount = ref(0);
const notFilterCount = ref(0);
const totalCount = ref(0);
const treeVo = ref([]);
// 获取机型
const getModelList = () => {
  getMeshModelStructureList({parentId: 0, pageSize: 999}).then(res => {
    if (res) {
      modelNumberList.value = res.rows;
    }
  })
}

// 获取批次号
const modelChange = (val) => {
  if (val) {
    getBatchNo({modelNumber: val}).then(res => {
      if (res) {    
        batchList.value = res.data.map(name => Object.fromEntries([['value', name]]))
      }
    })
  }
}
const querySearch = (queryString, cb) => {
  const results = queryString
    ? batchList.value.filter(item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
    : batchList.value
    console.log('result', results)
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString) => {
  return (item) => {
    return (
      item.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
// 验证文件格式是否正确
const beforeUpload = (file) => {
  let isFile = file.name.split('.')[file.name.split('.').length - 1] == 'zip' || file.name.split('.')[file.name.split('.').length - 1] == 'rar';
  const isLt = file.size / 1024 / 1024 < 500;
  if (!isFile) {
    ElMessage.error('导入文件格式不正确');
    return false;
  }
  if (!isLt) {
    ElMessage.error(`导入文件太大，请交由系统管理员进行处理`);
    return false;
  }
  //清空filelista
  uploadFiles.value = [];
  return isFile;
};
// 读取压缩文件
const componentImport = async (file) => {
  uploadFiles.value.push(file.file);
};

// zip包上传
const uploadRarOrZipFile = () => {
  let fd = new FormData();
  fd.append('file', uploadFiles.value[0]);
  fd.append('modelNumber', uploadForm.value.modelNumber);
  fd.append('batchNumber', uploadForm.value.batchNumber);
  dialogFormVisible.value = true;
  uploadMeshModelZip(fd).then(res => {
    dialogFormVisible.value = false;
    handleZipData.value = res.data;
    active.value++;
  }).finally(() => {
    dialogFormVisible.value = false;
  })
}
const step = (type) => {
  if (type === 'next') {
    if (active.value === 1) {
      if (!uploadForm.value.modelNumber) {
        ElMessage({ showClose: true, message: '请选择机型', type: 'error' });
        return;
      }
      if (!uploadForm.value.batchNumber) {
        ElMessage({ showClose: true, message: '请选择批次', type: 'error' });
        return;
      }
      if (!uploadFiles.value || uploadFiles.value.length == 0) {
        ElMessage({ showClose: true, message: '请先上传文件', type: 'error' });
        return;
      }
      // structureModel.value.forEach((el) => {
      //   if (el.mark === basicInfo.value.structureModelId) {
      //     basicInfo.value.parentId = el.id;
      //   }
      // });
      // updateFlag.value = true;
      // nextTick(() => {
      //   updateFlag.value = false;
      // });
      // zip rar压缩包导入
      
      uploadRarOrZipFile();
    }
    if (active.value === 2) {
      comfirmImport()
    }
    if (active.value === 3) {
    }
   
  } else {
    active.value--;
  }
};
// 确认上传
const comfirmImport = () => {
  if (handleModelData.value.initTableData.length === 0) {
    ElMessage({ showClose: true, message: '文件为空，请重新上传。', type: 'error' });
    return; 
  }
  uploadLoading.value = true;
  confirmUpload({
    tableName: props.tableName,
    boList: handleModelData.value.initTableData
  }).then(res => {
    if (res) {
      uploadLoading.value = false;
      uploadResult.value = res.data;
      totalCount.value = res.data.countVo.totalCount;
      notFilterCount.value = res.data.countVo.notFilterCount;
      filterCount.value = res.data.countVo.filterCount;
      treeVo.value = [res.data.treeVo];
      active.value++;
    }
  }).finally(() => {
    uploadLoading.value = false;
  })
}
const handleEvent = (data) => {
  if (data?.type === 'choose') {
    chooseData.value = data?.data || [];
    checkedTreeData.value = data?.treeData || [];
    computedUpdate.value = true;
    nextTick(() => {
      computedUpdate.value = false;
    });
  }
  if (data?.type === 'computed') {
    computedData.value = data?.data || [];
  }
  if (data?.type === 'confirmImport') {
    confirmImportTableData.value = data?.data?.tableData || [];
  }
};
// 完成组建
const finish = () => {
  emits('handleEvent', { component: 'List', type: 'finish', tableName: props.tableName });
};
// 取消
const cancel = () => {
  emits('handleEvent', { component: 'List', type: 'cancel', tableName: props.tableName });
};
onMounted(() => {
  getModelList();
});
</script>
<style lang="scss" scoped>
.upload_check {
  width: 100%;
  height: calc(100vh - 245px);
}
.upload_elements {
  padding: 10px;
  width: 100%;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: scroll;
  font-size: 12px;
  .steps {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
  }
  .upload {
    width: 800px;
    margin-top: 20px;
    .upload_content {
      width: 800px;
      height: 475px;
      text-align: center;
      .upload_form {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
    }
  }
  .upload_list,
  .upload_success {
    margin-top: 10px;
    // overflow: scroll;
    // min-height: calc(100vh - 251px);
    width: 100%;
  }
  .model-batch {
    padding: 10px;
    label {
      font-size: 16px;
    }
    span {
      margin-right: 20px;
      font-size: 14px;
    }
  }
  .option_btn {
    margin-top: 20px;
  }
  .upload_success {
    margin-top: 10px;
    .upload_success_message {
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  .finish {
    width: 600px;
    margin-top: 20px;
  }
  :deep(.el-step__title) {
    font-size: 12px;
  }
}
</style>
